//
//  RCMerchantAlbumDetailViewController.m
//  RocketProject
//
//  Created by Wu Chengwei on 13-9-30.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCMerchantAlbumDetailViewController.h"
#import "AppDelegate.h"
#import "NSArray+EX.h"
#import "NSString+NSString_Ex_.h"
#import "UIColor-Expanded.h"
#import "TravelException.h"
#import "CommonDefines.h"
#import "FrameworkRelativeDefines.h"
#import "RCMerchantPictureCell.h"
#import "GloableEngineService.h"
#import "BTCityAndSceneScrollViewController.h"
#import "RCMerchantUploadPhotoViewController.h"


#define kMaxRequestCount                  10

#define kButtonImageFile                  @"rc_discount_subView_button.png"
#define kButtonImageFile                  @"rc_discount_subView_button.png"
#define kNoLocationImageFile              @"rc_discount_subView_noContent.png"
#define kNoNetWrokImageFile               @"rc_discount_subView_noNetWork.png"
#define kNoNetworkButtonImage             @"rc_album_my_edit_button_back_normal.png"
#define kNoNetworkPressButtonImage        @"rc_album_my_edit_button_back_highlight.png"
#define kRightButtonImageFile          @"image_merchant_pictureAlbum.png"

@interface RCMerchantAlbumDetailViewController ()<RCMerchantPictureCellDelegate,LVPhotoPreviewViewControllerDelegate>

@property(nonatomic, assign) BOOL isRefreshData;
@property(nonatomic, assign) int totalCount;
@property(nonatomic, retain) UIView *wrongDataView;
@property(nonatomic, retain) UIImageView *wrongDataImageView;
@property(nonatomic, retain) UILabel *wrongDataLabel;
@property(nonatomic, retain) MBProgressHUDEx *progressHub;
@property(nonatomic, retain) UIButton *rightButton;

@end

@implementation RCMerchantAlbumDetailViewController

@synthesize requestID = _requestID;
@synthesize typeID = _typeID;
@synthesize merchantID = _merchantID;
@synthesize isRefreshData = _isRefreshData;
@synthesize currentOffset = _currentOffset;
@synthesize currentReturnNumber = _currentReturnNumber;
@synthesize totalCount = _totalCount;
@synthesize pictureDataInfo = _pictureDataInfo;
@synthesize itemListArray = _itemListArray;
@synthesize wrongDataView = _wrongDataView;
@synthesize wrongDataImageView = _wrongDataImageView;
@synthesize wrongDataLabel = _wrongDataLabel;
@synthesize progressHub = _progressHub;
@synthesize rightButton = _rightButton;

- (id)initWithMerchantID:(NSString *)merchantID andType:(NSString *)typeID
{
    self = [super init];
    if (self) {
        // Initialization code
        self.typeID = typeID;
        self.merchantID = merchantID;
        if (!_itemListArray) {
            _itemListArray = [[NSMutableArray alloc]initWithCapacity:1];
        }
        
    }
    return self;
}

-(void)dealloc{
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_requestID];
    self.progressHub.delegate = nil;
    self.progressHub = nil;
    self.typeID = nil;
    self.merchantID = nil;
    self.pictureDataInfo = nil;
    self.itemListArray = nil;
    self.wrongDataView = nil;
    self.wrongDataImageView = nil;
    self.wrongDataLabel = nil;
    self.rightButton = nil;
    [super dealloc];
}

-(void)loadView{
    [super loadView];
    _rightButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 0, 44, 44)];
    [_rightButton setImage:[UIImage imageNamed:kRightButtonImageFile]
                  forState:UIControlStateNormal];
    [_rightButton setImage:[UIImage imageNamed:kRightButtonImageFile]
                  forState:UIControlStateHighlighted];
    [_rightButton addTarget:self action:@selector(rightButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [self createRightBarButtonItemWithButton:_rightButton];
}

-(void)createWrongDataView{
    if (!_wrongDataView) {
        _wrongDataView = [[UIView alloc]initWithFrame:self.viewContainer.frame];
        _wrongDataView.backgroundColor = [UIColor clearColor];
        
        CGRect imageRect = CGRectMake(132, 0, 57, 57);
        imageRect.origin.y = self.viewContainer.frame.size.height/2 - 57;
        CGFloat height = imageRect.origin.y + 57;
        
        _wrongDataImageView = [[UIImageView alloc]initWithFrame:imageRect];
        _wrongDataImageView.backgroundColor = [UIColor clearColor];
        [_wrongDataView addSubview:_wrongDataImageView];
        
        height +=20;
        
        _wrongDataLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, height, 320, 14)];
        _wrongDataLabel.backgroundColor = [UIColor clearColor];
        _wrongDataLabel.textAlignment = UITextAlignmentCenter;
        _wrongDataLabel.font = [UIFont fontWithName:@"STHeitiSC-Medium" size:14];
        _wrongDataLabel.textColor = [UIColor colorWithHex:0xff717577];
        _wrongDataLabel.shadowColor = [UIColor colorWithHex:0xffffffff];
        _wrongDataLabel.shadowOffset = CGSizeMake(0, 1);
        [_wrongDataView addSubview:_wrongDataLabel];
        
        height +=26;
        
        
        UIButton *wrongDataButton = [[UIButton alloc]initWithFrame:CGRectMake(125, height, 70, 26)];
        NSString *normalImageString = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:kNoNetworkButtonImage];
        NSString *pressImageString = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:kNoNetworkPressButtonImage];
        UIImage *normalImage = [UIImage imageWithContentsOfFile:normalImageString];
        UIImage *pressImage = [UIImage imageWithContentsOfFile:pressImageString];
        [wrongDataButton setBackgroundImage:normalImage forState:UIControlStateNormal];
        [wrongDataButton setBackgroundImage:pressImage forState:UIControlStateHighlighted];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 7, 70, 13)];
        label.textAlignment = UITextAlignmentCenter;
        label.backgroundColor = [UIColor clearColor];
        label.textColor = [UIColor colorWithHex:0xff4d5357];
        label.font = [UIFont fontWithName:@"STHeitiSC-Medium" size:13];
        label.text = @"再试试";
        [wrongDataButton addSubview:label];
        [label release];
        
        [wrongDataButton addTarget:self action:@selector(noNetWorkButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        [_wrongDataView addSubview:wrongDataButton];
        [wrongDataButton release];
        
        [self.viewContainer addSubview:_wrongDataView];
        _wrongDataView.hidden = YES;
    }
}

-(void)noNetWorkButtonClicked{
    NetworkStatus status = [GloableEngineService sharedInstance].netWorkStatus;
    if (kNotReachable == status) {
        [RCAppDelegate alertWithNetworkError];
        return;
    }
    
    [self requestDataList:YES];
}

-(void)rightButtonClicked{
    
    if (![[GloableEngineService sharedInstance]alertLoginViewIfUnlogin:self]) {
        return;
    }
    
    RCMerchantUploadPhotoViewController *vc = [[RCMerchantUploadPhotoViewController alloc]initWithShopID:self.merchantID];
    [self.navigationController pushViewController:vc animated:YES];
    [vc release];
}


-(void)viewDidUnload{
    _currentOffset = 0;
    _currentReturnNumber = 0;
    _totalCount = 0;
    _isRefreshData = NO;
}


#pragma mark - Refresh delegate
- (void)refreshData //此接口必须被实现
{
    // 初始化页面计数
    currentPage = 0;
    
    // 判断网络状态
    if ([GloableEngineService sharedInstance].netWorkStatus == kNotReachable ){
        // 下拉/上拉操作数据获取完成后的处理
        [self finishLoadMoreData];
        
        [RCAppDelegate alertWithNetworkError];
        return;
    }
    
    
    // 请求数据
    [self.itemListArray removeAllObjects];
    [baseVCTableView reloadData];
    _currentOffset = 0;
    _currentReturnNumber = 0;
    _isRefreshData = YES;
    [self requestDataList:YES];
}



- (void)loadMoreData //此接口必须被实现
{
    // 判断网络状态
    if ([GloableEngineService sharedInstance].netWorkStatus == kNotReachable ){
        // 下拉/上拉操作数据获取完成后的处理
        [self finishLoadMoreData];
        
        [RCAppDelegate alertWithNetworkError];
        return;
    }
    
    // 请求数据
    [self requestDataList:NO];
}

-(void)requestDataList:(BOOL)isRefreshData{
    
    NetworkStatus status = [GloableEngineService sharedInstance].netWorkStatus;
    BOOL dataExist = (nil == _itemListArray) || ([_itemListArray count]==0);
    if (status == kNotReachable && dataExist) {
        [self createWrongDataView];
        NSString *filePath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:kNoNetWrokImageFile];
        UIImage *image = [UIImage imageWithContentsOfFile:filePath];
        [_wrongDataImageView setImage:image];
        _wrongDataLabel.text = @"没有感应到网络";
        baseVCTableView.hidden = YES;
        _wrongDataView.hidden = NO;
        return;
    }
    
    
    _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                               TopHeight:0
                                        withBottomHeight:0
                                           withLeftWidth:0
                                          withRightWidth:0
                                    withExclusiveObjects:nil];
    _progressHub.delegate = self;
    _progressHub.labelText = @"加载中...";
    [self.view addSubview:_progressHub];
    [self.view bringSubviewToFront:_progressHub];
    [_progressHub show:YES];
    
    _isRefreshData = isRefreshData;
    
    
    if (isRefreshData) {
        
        _requestID = [[IManager sharedInstance]requestMerchantPictureSubAlbunInfo:self.merchantID withTypeID:self.typeID withPn:0 withRn:[_itemListArray count] > 0 ? [_itemListArray count]:kMaxRequestCount withDelegate:self];
        
        
        
    }else{
        NSInteger offset = _currentOffset + _currentReturnNumber;
        
        _requestID = [[IManager sharedInstance]requestMerchantPictureSubAlbunInfo:self.merchantID withTypeID:self.typeID withPn:offset withRn:kMaxRequestCount withDelegate:self];
        
    }
}

#pragma UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  ceil(1.0*[_itemListArray count]/2);
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier = @"UITableViewPictureCell";
    
    RCMerchantPictureCell *pictureCell = (RCMerchantPictureCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (nil == pictureCell) {
        pictureCell = [[[RCMerchantPictureCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
        pictureCell.delegate = self;
        pictureCell.accessoryType = UITableViewCellAccessoryNone;
        pictureCell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    NSInteger row = [indexPath row];
    RCMerchantPictureItem *firstItemInfo = [_itemListArray safeObjectAtIndex:row *2];
    RCMerchantPictureItem *secondItemInfo = nil;
    if (row *2+1 < [_itemListArray count]) {
        secondItemInfo = [_itemListArray safeObjectAtIndex:row *2+1];
    }
    if (nil == firstItemInfo) {
        return nil;
    }
    [pictureCell bindData:firstItemInfo withFirstTag:row*2 withSecondItem:secondItemInfo withSecondTag:row*2+1];
    
    return pictureCell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    
}



#pragma mark - Request delegate

- (void)updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId
{
    if (_requestID == requestId)
    {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        BOOL dataExist = (nil == _itemListArray) || ([_itemListArray count]==0);
        if (dataExist) {
            if (nil != _itemListArray && [_itemListArray count]!=0) {
                [_itemListArray removeAllObjects];
            }
            [self createWrongDataView];
            NSString *filePath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:kNoNetWrokImageFile];
            UIImage *image = [UIImage imageWithContentsOfFile:filePath];
            [_wrongDataImageView setImage:image];
            _wrongDataLabel.text = @"没有图片信息";
            baseVCTableView.hidden = YES;
            _wrongDataView.hidden = NO;
        }
    }
}

-(void)updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId{
    if (_requestID == requestId && requestId != kInvalidRequestId) {
        
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        
        rcMerchantPictureSubAlbum *pictureDataModel = nil;
        
        pictureDataModel = (rcMerchantPictureSubAlbum *)dataModel;
        
        self.pictureDataInfo = pictureDataModel;
        
        _currentReturnNumber = pictureDataModel.rn;
        _currentOffset = pictureDataModel.pn;
        _totalCount = pictureDataModel.total;
        if (!_isRefreshData) {
            if (_currentReturnNumber > 0) {
                if (!_itemListArray) {
                    _itemListArray = [[NSMutableArray alloc]initWithCapacity:_currentReturnNumber];
                }
                
                //需要去重复
                NSMutableArray* originItemIdArr = [NSMutableArray array];
                
                for (RCMerchantPictureItem* originLocalItemDataModel in self.itemListArray)
                {
                    [originItemIdArr addObject:originLocalItemDataModel.photoID withDefaultValue:nil];
                }
                
                for (RCMerchantPictureItem* localItemDataModel in pictureDataModel.photoItemArray)
                {
                    if (![originItemIdArr containsObject:localItemDataModel.photoID])
                    {
                        [originItemIdArr addObject:localItemDataModel.photoID
                                  withDefaultValue:nil];
                        [self.itemListArray addObject:localItemDataModel
                                     withDefaultValue:nil];
                    }
                }
                
            }
            
            [self finishLoadMoreData];
        }else{
            if (_currentReturnNumber > 0) {
                if (!_itemListArray) {
                    _itemListArray = [[NSMutableArray alloc]initWithCapacity:_currentReturnNumber];
                }
                [_itemListArray removeAllObjects];
                [_itemListArray addObjectsFromArray:pictureDataModel.photoItemArray];
            }
            [self finishRefreshingData];
        }
        
        if (_wrongDataView && [self.itemListArray count] > 0)
        {
            _wrongDataView.hidden = YES;
        }
        
        if (0 == [self.itemListArray count])
        {
            if (!_wrongDataView)
            {
                [self createWrongDataView];
            }
            NSString *filePath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:kNoNetWrokImageFile];
            UIImage *image = [UIImage imageWithContentsOfFile:filePath];
            [_wrongDataImageView setImage:image];
            _wrongDataLabel.text = @"没有图片信息";
            _wrongDataView.hidden = NO;
        }
        
        baseVCTableView.hidden = NO;
        [baseVCTableView reloadData];
    }
    
    NSInteger currentTotal = [self.itemListArray count];
    if (currentTotal < self.pictureDataInfo.total) {
        [self addPullLoadMore];
    }else{
        [self noMoreData];
    }
    
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.titleLabelText = @"相册详情";
    self.navigationItem.titleView = [self createTitleView];
    if ( baseVCTableView != nil ) {
        self.view.autoresizingMask |= UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
        baseVCTableView.autoresizingMask |= UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
        baseVCTableView.backgroundColor = [UIColor clearColor];
        baseVCTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        baseVCTableView.frame = self.view.bounds;
//        CGRect tableViewNewFrame = CGRectMake(baseVCTableView.frame.origin.x,baseVCTableView.frame.origin.y+50,baseVCTableView.frame.size.width,baseVCTableView.frame.size.height-self.navigationController.navigationBar.frame.size.height-4);
//        baseVCTableView.frame = tableViewNewFrame;
        baseVCTableView.tableHeaderView = nil;
        baseVCTableView.tableFooterView = nil;
        [self addPullRefresh];
    }
    [self refreshData];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    baseVCTableView.backgroundColor = [UIColor clearColor];
}

-(void)gotoChildViewWithTag:(NSInteger)tag withImageView:(UIImageView *)imageView{
    if (tag < [_itemListArray count]) {
        if (self.pictureDataInfo.hasChild) {
            RCMerchantAlbumDetailViewController *vc = [[RCMerchantAlbumDetailViewController alloc]initWithMerchantID:self.merchantID andType:self.typeID];
            [self.navigationController pushViewController:vc animated:YES];
            [vc release];
        }else{
            BTCityAndSceneScrollViewController *vc = [[BTCityAndSceneScrollViewController alloc]initWithRequestParam:self.itemListArray CurrentPageNumber:tag IsContainPictureInfo:YES LoadFromWeb:YES];
            vc.shouldShowAnimation = YES;
            
            UIImage *headerImage = imageView.image;
            
            
            CGRect rect = [self.view.superview convertRect:imageView.bounds fromView:imageView];
            rect.origin.y +=64;
            [vc setFromImage:headerImage fromWindowRect:rect];
            vc.animationDelegate = self;
            
            [RCAppDelegate.tabBarController setModalPresentationStyle:UIModalPresentationCurrentContext];
            [RCAppDelegate.tabBarController presentViewControllerWithCompatibility:vc animated:NO];
            [vc release];
        }
    }
}

#pragma photoDelegate

-(BOOL)shouldAnimatedWhenViewDidDisappearForPhotoPreviewViewController:(BTCityAndSceneScrollViewController *)vc {
    return YES;
}

-(BOOL)shouldAnimatedWhenViewDidAppearForPhotoPreviewViewController:(BTCityAndSceneScrollViewController *)vc {
    return YES;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
